using System.Collections;
using System.Collections.Generic;
using QFramework;
using UnityEngine;
using UnityEngine.UI;

public class TopThree : MonoBehaviour
{
    // Start is called before the first frame update
    public List<GameObject> ClassATops;
    public List<GameObject> ClassBTops;
    void Start()
    {
        //ClassA的top3
        StringEventSystem.Global.Register(EventID.ClassJieSuanTop3, (List<GameObject> students) =>{
            OnClassJieSuanEnded(students);
        }).UnRegisterWhenGameObjectDestroyed(gameObject);
    }

    void OnClassJieSuanEnded(List<GameObject> students)
    {
        List<GameObject> classAStudents = new List<GameObject>();
        List<GameObject> classBStudents = new List<GameObject>();
        
        // 先创建两个列表的副本，避免在遍历时修改原集合
        var studentsCopy = new List<GameObject>(students);
        
        //遍历studentsNodes的副本
        foreach (var student in studentsCopy)
        {
            //获取学生答题数
            int studentType = student.GetComponentInChildren<Student>().getClassType();
            if (studentType == 1)
            {
                classAStudents.Add(student);
            }else{
                classBStudents.Add(student);
            }
        }
        //然后根据每个学生答对的积分，对list进行排序
        classAStudents.Sort((x, y) =>
        {
            return y.GetComponentInChildren<Student>().getJifen().CompareTo(x.GetComponentInChildren<Student>().getJifen());
        });
        //然后根据每个学生答对的积分，对list进行排序
        classBStudents.Sort((x, y) =>
        {
            return y.GetComponentInChildren<Student>().getJifen().CompareTo(x.GetComponentInChildren<Student>().getJifen());
        });

        ShowTop3(classAStudents,ClassATops);
        ShowTop3(classBStudents,ClassBTops);

    }
    void ShowTop3(List<GameObject> students,List<GameObject> Top3){
        // 取前三名展示
        int countToDisplay = Mathf.Min(students.Count, 3); // 取实际数量和3中的较小值

        for (int i = 0; i < countToDisplay; i++)
        {
            // 更新头像
            ImageLoader.Instance.LoadImageFromUrl(
                Top3[i].transform.GetChild(0).GetComponent<Image>(), 
                students[i].GetComponentInChildren<Student>().getAvatarUrl()
            );
        }     
        // 如果学生数量少于3，清空剩余的 Tops
        for (int i = countToDisplay; i < Top3.Count; i++)
        {
            Top3[i].SetActive(false); // 隐藏多余的 UI 元素
        }

    }
}
